import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";

export async function PUT(
  request: Request,
  { params }: { params: { orderId: string } }
) {
  try {
    const orderId = params.orderId;
    const data = await request.json();

    // 检查订单是否存在
    const existingOrder = await prisma.order.findUnique({
      where: { orderId },
    });

    if (!existingOrder) {
      return new NextResponse(JSON.stringify({ error: "订单不存在" }), {
        status: 404,
        headers: { "Content-Type": "application/json" },
      });
    }

    // 更新订单信息
    const updatedOrder = await prisma.order.update({
      where: { orderId },
      data: {
        state: data.orderState,
        goodsAD: data.goodsAddress,
        tel: data.tel,
        oName: data.customerName,
      },
    });

    return new NextResponse(
      JSON.stringify({
        orderId: updatedOrder.orderId,
        openId: updatedOrder.openId,
        goodsId: updatedOrder.goodsId,
        orderTime: updatedOrder.createTime
          ? updatedOrder.createTime.toISOString()
          : "",
        orderState: updatedOrder.state,
        goodsAddress: updatedOrder.goodsAD,
        tel: updatedOrder.tel,
        customerName: updatedOrder.oName,
        trading: updatedOrder.trading,
      }),
      {
        status: 200,
        headers: { "Content-Type": "application/json" },
      }
    );
  } catch (error) {
    console.error("更新订单失败:", error);
    return new NextResponse(JSON.stringify({ error: "更新订单失败" }), {
      status: 500,
      headers: { "Content-Type": "application/json" },
    });
  }
}
